<template>
	<view>
		<cu-custom bgColor="bg-gradual-blue-light" :isBack="true" backText="返回" :title="funcType == 'add' ? '新增家庭成员' : '编辑家庭成员'"></cu-custom>
		<view style="display: flex;align-items: center;justify-content: center; padding: 30rpx 0rpx;">
			<view @tap="ChooseImage('photo')" class="cu-avatar round xxl bg-white"  :style="[{ backgroundImage:'url(' + photo + ')' }]">
				<view class="round text-center text-xs" style="background-color: #F85E64;color: #FFFFFF;width: 150rpx;height: 40rpx;line-height: 40rpx;margin-top: 120rpx;">上传真人头像</view>
			</view>
		</view>
		<zh-picker
			pickerRef="holderRelation"
			label="他（她）是我的"
			labelWidth="230rpx"
			labelAlign="left"
			justifyContent="space-between"
			mode="selector"
			:options="dictData.holderRelation ? dictData.holderRelation : []"
			rightIconClass="text-gray"
			:value="formData.holderRelation"
			placeholder="请选择与我关系"
			themeColor="#FC7983"
			@pickerChange="onHolderRelationChange($event)"
			ref="holderRelation"
		></zh-picker>
		<zh-input type="text" v-model="formData.fullName" maxlength="50" placeholder="请输入姓名" label="姓名" labelAlign="left" inputAlign="right"></zh-input>
		<zh-picker
			label="证件类型"
			labelAlign="left"
			justifyContent="space-between"
			rightIconClass="text-gray"
			pickerRef="cardTypeRef"
			mode="selector"
			:value="formData.cardType"
			:options="dictData.cardType ? dictData.cardType : []"
			placeholder="请选择证件类型"
			themeColor="#FC7983"
			@pickerChange="onCardTypeChange($event)"
			ref="cardTypeRef"
		></zh-picker>
		<zh-input type="idcard" v-model="formData.idcard" label="证件号码" labelAlign="left" inputAlign="right" maxlength="20" placeholder="请输入证件号码"></zh-input>
		<zh-input type="number" v-model="formData.cellphone" label="手机号码" labelAlign="left" inputAlign="right" maxlength="11" placeholder="请输入手机号码"></zh-input>
		<zh-picker
			pickerRef="sex"
			label="性别"
			labelAlign="left"
			justifyContent="space-between"
			mode="selector"
			:options="sexData"
			rightIconClass="text-gray"
			:value="formData.sex"
			placeholder="请选择性别"
			themeColor="#FC7983"
			@pickerChange="onSexChange($event)"
			ref="sex"
		></zh-picker>
		<zh-picker
			pickerRef="birthday"
			mode="date"
			startYear="1920"
			label="出生日期"
			themeColor="#FC7983"
			labelAlign="left"
			rightIconClass="text-gray"
			justifyContent="space-between"
			:value="formData.birthday"
			fields="day"
			ref="birthday"
			@pickerChange="onBirthdayChange($event)"
		></zh-picker>
		<zh-country
			label="国家/地区"
			labelWidth="200rpx"
			labelAlign="left"
			placeholder="请选择国家/地区"
			justifyContent="space-between"
			ref="countrySelect"
			addressRef="countrySelect"
			:value="formData.country ? formData.country : 'cn'"
			rightIconClass="text-gray"
			@selectChange="countryChange"
		></zh-country>
		<view style="padding: 0 30rpx 0 30rpx;width: 100%;" class="margin-top">
		<cg-slider @event="verifySuccess"></cg-slider>
		</view>
		<view style="padding: 0 30rpx 0 30rpx;width: 100%;margin-top: 10rpx;" class="flex flex-direction ">
			<button :disabled="disabled" class="cu-btn shadow margin-tb-sm lg bg-gradual-blue-light" @tap="save">保存</button>
			<button :disabled="disabled" v-if="funcType == 'edit'" class="cu-btn shadow margin-tb-sm lg bg-gradual-red" @tap="del">删除</button>
		</view>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
import store from '@/store';
import api from '@/api/system/familyMember.js';
import commonApi from '@/api/system/common.js';
import reqConfig from '@/common/config/reqConfig.js'
export default {
	data() {
		return {
			funcType: 'add',
			memberId: null,
			masterId: store.state.hh_user.personId,
			formData: {},
			sexData: [{ dictKey: '1', dictValue: '男' }, { dictKey: '2', dictValue: '女' }],
			dictData: {},
			disabled: true,
			photo: 'https://ewm.rsj.jinhua.gov.cn/jhrs/api/common/file/show/jycy/3babbcdbf12d41ea891693fb58c9bb23',
			userId:store.state.hh_user.userId,
			fullName:store.state.hh_user.fullName,
		};
	},
	onLoad: function(option) {
		if (this.$Route.query) {
			if (this.$Route.query.funcType) {
				this.funcType = this.$Route.query.funcType;
			}
			if (this.$Route.query.memberId) {
				this.memberId = this.$Route.query.memberId;
				this.getDetail();
			}
		}
	},
	onReady() {
		// 数据字典初始化
		const data = {};
		data.dictFields = 'holderRelation,cardType';
		this.$http
			.post(commonApi.getDictBatch, data)
			.then(res => {
				this.dictData = res.result;
			})
			.catch(error => {});
	},
	methods: {
		onHolderRelationChange(e) {
			this.formData.holderRelation = e.value;
		},
		onSexChange(e) {
			this.formData.sex = e.value;
		},
		onBirthdayChange(e) {
			this.formData.birthday = e.value;
		},
		onCardTypeChange(e) {
			this.formData.cardType = e.value;
		},
		countryChange(e) {
			this.formData.country = e.classname;
			this.formData.countryName = e.county;
			this.showCountryFlag = false;
		},
		getDetail() {
			const data = {};
			data.memberId = this.memberId;
			this.$http
				.post(api.getDetail, data)
				.then(res => {
					this.formData = res.result;
					this.photo=res.result.photo?res.result.photo:'https://ewm.rsj.jinhua.gov.cn/jhrs/api/common/file/show/jycy/3babbcdbf12d41ea891693fb58c9bb23'
				})
				.catch(error => {});
		},
		verifySuccess(e) {
			if (e.flag) {
				this.disabled = false;
			}
		},
		save() {
			let saveApi = '';
			const data = { ...this.formData };
			if(!data.cardType){
				uni.showToast({
					title: '请输入证件类型',
					icon: 'none',
					duration:2000
				});
				return ;
			}
			if(!data.idcard){
				uni.showToast({
					title: '请输入身份证或护照号',
					icon: 'none',
					duration:2000
				});
				return
			}
			if(!data.fullName){
				uni.showToast({
					title: '请输入姓名',
					icon: 'none',
					duration:2000
				});
				return
			}
			if(data.cellphone){
				if (!this.$validate.isPhone(data.cellphone)) {
				  uni.showToast({
				    icon: 'none',
				    title: '请输入正确的手机号',
					duration:2000
				  })
				  return
				}
			}
			if(data.cardType=='01'){
				if(!this.$validate.isIdcard(data.idcard)){
					uni.showToast({
					  icon: 'none',
					  title: '请输入正确的身份证号',
					  duration:2000
					})
					return
				}
			}
			if (this.funcType == 'add') {
				saveApi = api.add;
				data.masterId = this.masterId;
			} else {
				saveApi = api.edit;
			}
			this.$http
				.post(saveApi, data)
				.then(res => {
					this.$refs.uToast.show({
						title: '保存成功',
						// 如果不传此type参数，默认为default，也可以手动写上 type: 'default'
						type: 'success',
						position: 'top',
						// 如果不需要图标，请设置为false
						icon: false,
						back: true
					});
					this.disabled = true;
				})
				.catch(error => {});
		},
		del() {
			const data = {};
			data.memberId = this.memberId;
			this.$http
				.post(api.del, data)
				.then(res => {
					this.$refs.uToast.show({
						title: '删除成功',
						// 如果不传此type参数，默认为default，也可以手动写上 type: 'default'
						type: 'success',
						position: 'top',
						// 如果不需要图标，请设置为false
						icon: false,
						back: true
					});
				})
				.catch(error => {});
		},
		ChooseImage(type) {
			uni.chooseImage({
				count: 1, //默认9
				sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
				sourceType: ['album'], //从相册选择
				success: (res) => {
					new Promise((resolve, reject) => {
					    uni.uploadFile({
					        url: reqConfig.jhrsUrl+commonApi.uploadFile, //仅为示例，非真实的接口地址
					        filePath: res.tempFilePaths[0],
					        name: 'file',
					        formData: {
					            'uploaderId': this.userId,
								'uploader':this.fullName,
								'fileClassCode':'20'
					        },
					        success: function (uploadFileRes) {
					    		const fileRes = JSON.parse(uploadFileRes.data)
								resolve(fileRes);
					        },
					    	fail:function(error){
								reject(err);
					    		
					    	}
					    })
					}).then(data => {
							console.log(data);
							if(!data){
								uni.showToast({
									icon: 'none',
									title: "上传文件失败",
									duration:2000
								})
								return
							}
							if(data &&data.code!== 0){
								uni.showToast({
									icon: 'none',
									title: data.message,
									duration:2000
								})
								return
							}
							const file = data.result.file
							if(!file.flag){
								uni.showToast({
									icon: 'none',
									title: "上传文件失败",
									duration:2000
								})
								return
							}
							const showId = file.showId
							let url = reqConfig.jhrsUrl+commonApi.showFile+"/"+showId
							console.log(type)
							if(type=='photo'){
								this.photo=url
								this.formData.photo=url
								if(this.photoShowId){
									if(showId!=this.photoShowId){
										this.DelImg(this.photoShowId)
									}
								}
								
								this.formData.photoShowId = showId
							}
						}).catch(err => {
							uni.showToast({
								icon: 'none',
								title: '上传文件失败：'+err.message,
								duration:2000
							})
						})
				}
			});
		},
		DelImg(showId) {
			const data = {};
			data.uploaderId=this.userId
			data.uploader=this.fullName
			this.$jhrsHttp.post(commonApi.delFile+"/"+showId, data).then(res => {
			}).catch(error => {
				
			})
		},
	}
};
</script>

<style lang="scss"></style>
